<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      #text {
        border: solid;
        width: 400px;
        height: 200px;
        overflow: hidden;
        font-size: 3rem;
      }

      #text textarea {
        width: 400px;
        height: 200px;
        border: none;
        outline: none;
        font-size: 3rem;
      }
    </style>
  </head>
  <body>
    <div contenteditable>hello</div>

    <div id="text">hello jack</div>
    <script>
      const text = document.getElementById("text");
      text.onclick = function () {
        // 1. 创建textarea
        const textarea = document.createElement("textarea");
        // 2. 将text中的html放到textarea中
        textarea.value = this.innerHTML;
        // 3. 使用textarea覆盖text中的内容
        this.innerHTML = "";
        this.append(textarea);
        // 4. textarea获取焦点
        textarea.focus();
        // 5. 阻止textarea click事件冒泡
        textarea.onclick = (e) => e.stopPropagation();
        // 6. textarea 失去焦点后，textarea内容重新覆盖text
        textarea.onblur = function () {
          text.innerHTML = this.value;
        };
        // 7. 添加enter键盘事件，按下enter后，textarea内容重新覆盖text
        textarea.onkeydown = function (e) {
          if (e.key === "Enter") {
            textarea.onblur = null;
            text.innerHTML = this.value;
          }
        };
      };
    </script>
  </body>
</html>
